package edu.cuny.baruch.cis9590.library.gui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

import edu.cuny.baruch.cis9590.library.entities.Book;

final class BookTable extends JTable {
    
    private final BookTableModel model = new BookTableModel();
    
    public BookTable() {
        super();
        super.setModel(model);
    }
    
    public void clear() {
        setBooks(Collections.EMPTY_LIST);
    }
    
    public Book getSelectedBook() {
        int row = getSelectedRow();
        if (row == -1) {
            return null;
        }
        return model.getBook(row);
    }
    
    public void refresh() {
        model.refresh();
    }
    
    public void setBooks(List<Book> books) {
        model.setBooks(books);
    }
    
    @Override
    public void setModel(TableModel model) {
    }
    
    private static final class BookTableModel extends AbstractTableModel {
        
        private static final String[] COLUMN_NAMES = new String[] {"Title", "Author", "Call Number", "Status"};
        
        private List<Book> books = Collections.EMPTY_LIST;
        
        public Book getBook(int number) {
            return books.get(number);
        }
        
        @Override
        public Class<String> getColumnClass(int columnIndex) {
            return String.class;
        }
        
        @Override
        public int getColumnCount() {
            return COLUMN_NAMES.length;
        }
        
        @Override
        public String getColumnName(int columnIndex) {
            return COLUMN_NAMES[columnIndex];
        }
        
        @Override
        public int getRowCount() {
            return books.size();
        }
        
        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Book book = books.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return book.getTitle();
                case 1:
                    return book.getAuthor();
                case 2:
                    return book.getCallNumber();
                case 3:
                    return String.valueOf(book.getStatus());
            }
            return null;
        }
        
        public void refresh() {
            setBooks(books);
        }
        
        public void setBooks(List<Book> books) {
            this.books = new ArrayList<Book>();
            for (Book book : books) {
                if (book.getStatus() != 'P' && book.getStatus() != 'D')
                this.books.add(book);
            }
            fireTableDataChanged();
        }
    }
}
